import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography, Row, Col, Divider } from 'antd';
import { UserOutlined, MailOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../store/AuthContext';

const { Title, Text, Paragraph } = Typography;

const Register: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [codeLoading, setCodeLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [form] = Form.useForm();
  const { register, verifyEmail, sendLoginCode } = useAuth();
  const navigate = useNavigate();

  const handleSendCode = async () => {
    const email = form.getFieldValue('email');
    if (!email) {
      message.warning('请先输入邮箱');
      return;
    }
    
    setCodeLoading(true);
    try {
      await sendLoginCode(email);
      message.success('验证码已发送，请查收邮箱');
      setCountdown(60);
      
      // 开始倒计时
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error: any) {
      if (error.status === 429) {
        message.error(error.message);
        setCountdown(error.timeLeft || 60);
        
        // 开始倒计时
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        message.error(error.message || '发送失败');
      }
    } finally {
      setCodeLoading(false);
    }
  };

  const handleCompleteRegister = async () => {
    const values = form.getFieldsValue();
    
    if (values.password !== values.confirmPassword) {
      message.error('两次输入的密码不一致');
      return;
    }
    
    if (!values.username || !values.email || !values.password || !values.code) {
      message.error('请填写完整信息');
      return;
    }

    setLoading(true);
    try {
      // 先注册用户（不包含个人信息）
      await register({
        username: values.username,
        email: values.email,
        password: values.password
      });
      
      // 然后验证邮箱
      await verifyEmail(values.email, values.code);
      
      message.success('注册完成！正在跳转到登录页面...');
      setTimeout(() => {
        navigate('/login');
      }, 2000);
    } catch (error: any) {
      message.error(error.message || '注册失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px',
      position: 'relative',
      overflow: 'hidden'
    }}>
      {/* 背景装饰 */}
      <div style={{
        position: 'absolute',
        top: '-50%',
        left: '-50%',
        width: '200%',
        height: '200%',
        background: 'radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px)',
        backgroundSize: '50px 50px',
        animation: 'float 20s infinite linear',
        pointerEvents: 'none'
      }} />
      
      <Card 
        style={{ 
          width: '100%', 
          maxWidth: 600,
          boxShadow: '0 20px 40px rgba(0,0,0,0.1)',
          borderRadius: '20px',
          border: 'none',
          overflow: 'hidden',
          position: 'relative'
        }}
        bodyStyle={{ padding: '40px' }}
      >
        {/* 卡片顶部装饰 */}
        <div style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          height: '4px',
          background: 'linear-gradient(90deg, #667eea, #764ba2, #f093fb)',
          backgroundSize: '200% 200%',
          animation: 'gradient 3s ease infinite'
        }} />
        
        <div style={{ textAlign: 'center', marginBottom: 40 }}>
          <div style={{
            width: 80,
            height: 80,
            background: 'linear-gradient(135deg, #667eea, #764ba2)',
            borderRadius: '50%',
            margin: '0 auto 20px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '32px',
            color: 'white',
            boxShadow: '0 10px 30px rgba(102, 126, 234, 0.3)'
          }}>
            🎓
          </div>
          <Title level={2} style={{ 
            color: '#2c3e50', 
            marginBottom: 8,
            fontWeight: 'bold',
            fontSize: '28px'
          }}>
            加入 LinkMate
          </Title>
          <Paragraph style={{ 
            color: '#7f8c8d', 
            marginBottom: 0,
            fontSize: '16px'
          }}>
            开启你的学习之旅
          </Paragraph>
        </div>

        <Form
          form={form}
          layout="vertical"
          size="large"
        >
          <Form.Item
            name="username"
            label="用户名"
            rules={[
              { required: true, message: '请输入用户名' },
              { min: 3, message: '用户名至少3个字符' },
              { max: 50, message: '用户名最多50个字符' }
            ]}
            style={{ marginBottom: 24 }}
          >
            <Input 
              prefix={<UserOutlined style={{ color: '#667eea' }} />}
              placeholder="用户名" 
              style={{ 
                height: '50px',
                borderRadius: '10px',
                border: '2px solid #f0f0f0',
                fontSize: '16px'
              }}
            />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
            style={{ marginBottom: 24 }}
          >
            <Input 
              prefix={<MailOutlined style={{ color: '#667eea' }} />}
              placeholder="邮箱地址" 
              style={{ 
                height: '50px',
                borderRadius: '10px',
                border: '2px solid #f0f0f0',
                fontSize: '16px'
              }}
            />
          </Form.Item>

          <Row gutter={16}>
            <Col xs={24} sm={12}>
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 8, message: '密码至少8位' },
                  { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{8,}$/, message: '密码必须包含字母和数字' }
                ]}
                style={{ marginBottom: 24 }}
              >
                <Input.Password 
                  prefix={<LockOutlined style={{ color: '#667eea' }} />}
                  placeholder="密码" 
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                  style={{ 
                    height: '50px',
                    borderRadius: '10px',
                    border: '2px solid #f0f0f0',
                    fontSize: '16px'
                  }}
                />
              </Form.Item>
            </Col>
            
            <Col xs={24} sm={12}>
              <Form.Item
                name="confirmPassword"
                label="确认密码"
                rules={[{ required: true, message: '请确认密码' }]}
                style={{ marginBottom: 24 }}
              >
                <Input.Password 
                  prefix={<LockOutlined style={{ color: '#667eea' }} />}
                  placeholder="确认密码" 
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                  style={{ 
                    height: '50px',
                    borderRadius: '10px',
                    border: '2px solid #f0f0f0',
                    fontSize: '16px'
                  }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider style={{ margin: '30px 0' }}>
            <Text type="secondary" style={{ fontSize: '14px' }}>邮箱验证</Text>
          </Divider>

          <Row gutter={16}>
            <Col xs={24} sm={16}>
              <Form.Item
                name="code"
                label="验证码"
                rules={[{ required: true, message: '请输入验证码' }]}
                style={{ marginBottom: 32 }}
              >
                <Input
                  placeholder="验证码"
                  style={{ 
                    height: '50px',
                    borderRadius: '10px 0 0 10px',
                    border: '2px solid #f0f0f0',
                    fontSize: '16px'
                  }}
                />
              </Form.Item>
            </Col>
            
            <Col xs={24} sm={8}>
              <Form.Item label=" " style={{ marginBottom: 32 }}>
                <Button
                  loading={codeLoading}
                  disabled={countdown > 0}
                  onClick={handleSendCode}
                  style={{
                    width: '100%',
                    height: '50px',
                    borderRadius: '0 10px 10px 0',
                    border: '2px solid #667eea',
                    background: countdown > 0 ? '#f5f5f5' : 'white',
                    color: countdown > 0 ? '#999' : '#667eea',
                    fontWeight: 'bold',
                    fontSize: '16px'
                  }}
                >
                  {codeLoading ? '发送中' : countdown > 0 ? `${countdown}s` : '获取验证码'}
                </Button>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item style={{ marginTop: 30, marginBottom: 0 }}>
            <Button
              type="primary"
              loading={loading}
              onClick={handleCompleteRegister}
              style={{ 
                width: '100%',
                height: '50px',
                borderRadius: '10px',
                fontSize: '16px',
                fontWeight: 'bold',
                background: 'linear-gradient(135deg, #667eea, #764ba2)',
                border: 'none',
                boxShadow: '0 8px 20px rgba(102, 126, 234, 0.3)'
              }}
            >
              {loading ? '注册中...' : '完成注册'}
            </Button>
          </Form.Item>
        </Form>

        <Divider style={{ margin: '30px 0 20px' }}>
          <Text type="secondary" style={{ fontSize: '14px' }}>或</Text>
        </Divider>

        <div style={{ textAlign: 'center' }}>
          <Text type="secondary" style={{ fontSize: '16px' }}>
            已有账号？{' '}
            <Button 
              type="link" 
              onClick={() => navigate('/login')}
              style={{ 
                padding: 0,
                fontSize: '16px',
                fontWeight: 'bold',
                color: '#667eea'
              }}
            >
              立即登录
            </Button>
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default Register;
